package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("SubjectRestController")
public class SubjectRestController extends CmiEmaController {

	/**
	 * Create a new Subject entity
	 * 
	 */
	@RequestMapping(value = "/newSubject", method = RequestMethod.POST)
	@ResponseBody
	public Object newSubject(@RequestBody Subject subject) {
		subjectService.saveSubject(subject);
		return JSONObject.parse(cmiPsonService.toJsonString(subjectDAO.findSubjectByPrimaryKey(subject.getId()), 2));
	}

	@RequestMapping(value = "/restNewSubject", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewSubject(@RequestBody String subjectJson) {
		Subject subject = new Gson().fromJson(subjectJson, Subject.class);
		appendReferences(subject);
		subjectService.saveSubject(subject);
		return JSONObject.parse(cmiPsonService.toJsonString(subjectDAO.findSubjectByPrimaryKey(subject.getId()), 2));
	}

	@RequestMapping(value = "/saveSubject", method = RequestMethod.PUT)
	@ResponseBody
	public Subject saveSubject(@RequestBody Subject subject) {
		subjectService.saveSubject(subject);
		return subjectDAO.findSubjectByPrimaryKey(subject.getId());
	}

	@RequestMapping(value = "/restSaveSubject", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveSubject(@RequestBody String subjectJson) {
		Subject subject = new Gson().fromJson(subjectJson, Subject.class);
		appendReferences(subject);
		CmiPsonService cmiPsonService = new CmiPsonService();
		subjectService.saveSubject(subject);
		return JSONObject.parse(cmiPsonService.toJsonString(subjectDAO.findSubjectByPrimaryKey(subject.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteSubject/{subjectId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteSubject(@PathVariable Integer subjectId) {
		Subject subject = subjectDAO.findSubjectByPrimaryKey(subjectId);
		subjectService.deleteSubject(subject);
	}

	@RequestMapping(value = "/restConfirmDeleteSubjects")
	@ResponseBody
	public Object restConfirmDeleteSubjects(@RequestBody Set<Integer> deleteSubjectsIds) {
		Set<Subject> deleteSubjects = subjectDAO.findSubjectsByIds(deleteSubjectsIds);
		Set<Subject> referencedSubjects = subjectService.loadReferenceSubjects(deleteSubjects);
		deleteSubjects.removeAll(referencedSubjects);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedSubjects);
		jsonObject.put("deleteEntitys", deleteSubjects);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteSubjects")
	@ResponseBody
	public Object restDeleteSubjects(@RequestBody Set<Subject> deleteSubjects) {
		Iterator<Subject> iterator = deleteSubjects.iterator();
		while (iterator.hasNext()) {
			Subject currentSubject = iterator.next();
			subjectService.deleteSubject(currentSubject);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listSubjects");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadSubject/{subjectId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadSubject(@PathVariable Integer subjectId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(subjectDAO.findSubjectByPrimaryKey(subjectId), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadSubjectDetects/{subjectId}/detects/{relateddetectId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadSubjectDetects(@PathVariable Integer subjectId, @PathVariable Integer relateddetectId,
			@RequestBody CmiPagination cmiPagination) {
		Detect detect = detectDAO.findDetectByPrimaryKey(relateddetectId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(detect, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadSubjectEvents/{subjectId}/events/{relatedeventId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadSubjectEvents(@PathVariable Integer subjectId, @PathVariable Integer relatedeventId,
			@RequestBody CmiPagination cmiPagination) {
		Event event = eventDAO.findEventByPrimaryKey(relatedeventId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(event, 2, cmiPagination));
	}

	public void appendReferences(Subject subject) {

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Detect> detectsForSubject = new HashSet<>();
		for (Detect detect_Subject : subject.getDetectsForSubject()) {
			detectsForSubject.add(detectService.findDetectByPrimaryKey(detect_Subject.getId()));
		}
		subject.setDetectsForSubject(detectsForSubject);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Event> eventsForSubject = new HashSet<>();
		for (Event event_Subject : subject.getEventsForSubject()) {
			eventsForSubject.add(eventService.findEventByPrimaryKey(event_Subject.getId()));
		}
		subject.setEventsForSubject(eventsForSubject);
	}

	@RequestMapping(value = "/restGetSubjectDetects/{subjectId}/detects", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetSubjectDetects(@PathVariable Integer subjectId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(subjectDAO.findSubjectByPrimaryKey(subjectId).getDetectsForSubject(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetSubjectEvents/{subjectId}/events", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetSubjectEvents(@PathVariable Integer subjectId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(subjectDAO.findSubjectByPrimaryKey(subjectId).getEventsForSubject(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListSubjects", method = RequestMethod.GET)
	@ResponseBody
	public Object restListSubjects() {
		return JSONObject.parse(cmiPsonService.toJsonString(subjectService.loadSubjects(), 2));
	}

	@RequestMapping(value = "/restListSubjectsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListSubjectsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = subjectPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Subject> subjects = subjectDAO.findAllSubjects(startResult, cmiPagination.getPaginationSize());
		String subjectString = cmiPsonService.toPsonString(subjects, 2, cmiPagination);

		return JSONObject.parse(subjectString);
	}

	@RequestMapping("/subjectSelectBox")
	@ResponseBody
	public JSONObject subjectSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键

			// 被引用键
			case "Detect":
				entitySet = detectService.loadDetectsByIdSet(searchValue);
				break;
			case "Event":
				entitySet = eventService.loadEventsByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Detect":
				entitySet = detectDAO.findAllDetects((pageNumber - 1) * paginationSize, paginationSize);
				count = detectService.countDetects();
				break;
			case "Event":
				entitySet = eventDAO.findAllEvents((pageNumber - 1) * paginationSize, paginationSize);
				count = eventService.countEvents();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Detect":
				entitySet = detectDAO.findDetectByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = detectService.countDetectsByName(queryword);
				break;
			case "Event":
				entitySet = eventDAO.findEventByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = eventService.countEventsByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
